package commande.os.linux;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;

import librairies.liste.interfaces.IListeE;
import librairies.liste.list.ListeDCE;

import commande.Outils;
import commande.interfaces.IConsole;
import commande.outils.Processus;

/**
 * Gestion de la console sous linux. 
 * 
 * @author mlozach
 */
public class ConsoleLinux implements IConsole
{
	private Outils outils;
	
	public ConsoleLinux()
	{
		this.outils = Outils.getInstance();
	}
	
	@Override
	public IListeE<String> rechercheFichier(String racine, String recherche)
	{
		Process pro = null;
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		IListeE<String> retour = new ListeDCE<String>();
		
		try
		{
			Runtime runtime = Runtime.getRuntime();
			pro = runtime.exec(new String[] { "find", racine, "-name", recherche, "-print"} );
			
    		is = pro.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String ligne = null;
            
            while((ligne = br.readLine()) != null)
            {
               retour.add(ligne);
            }
        } 
		catch (IOException ioe)
		{
            ioe.printStackTrace();
        }
		return retour;
	}

	@Override
	public Processus execution(String nom, String argument) throws IOException
	{
		if(nom == null || nom.length() == 0) return null;
		
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		Processus process = new Processus();
		Process pro = null;

		try
		{
			process.setNomProcessus(nom);
			
			Runtime runtime = Runtime.getRuntime();
			if(argument != null && argument.length() != 0)
			{
				pro = runtime.exec(new String[] {nom, argument} );
			} 
			else
			{
				pro = runtime.exec(new String[] {nom} );
			}

			Field f = pro.getClass().getDeclaredField("pid");
			f.setAccessible(true);
			process.setPid(f.get(pro).toString());	
			
    		is = pro.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String ligne = null;
            
            while((ligne = br.readLine()) != null)
            {
              outils.out(ligne);
            }
        } 
		catch (SecurityException e) 
        {
			e.printStackTrace();
		} catch (NoSuchFieldException e) 
		{
			e.printStackTrace();
		} catch (IllegalArgumentException e) 
		{
			e.printStackTrace();
		} catch (IllegalAccessException e) 
		{
			e.printStackTrace();
		}
		return process;
	}
}
